<template>
  <div class="container">
    <!--头部筛选 start-->
    <div class="flex-row justify-between p_b10">
      <div>
        <el-input size="small" v-model="params.filter" placeholder="搜索关键词..." class="m_r10 width200"></el-input>
        <el-button size="small" type="primary" icon="el-icon-search" @click="onPageChange(1)"></el-button>
        <el-button size="small" type="primary" @click="onPageChange(1)">刷新</el-button>
      </div>
      <div>
        <el-button size="small" type="primary" @click="toggleEditorModal(true)">新增商品</el-button>
      </div>
    </div>
    <!--头部筛选 end-->

    <!--列表数据 start-->
    <el-table :data="tableData" border size="mini">
      <el-table-column prop="id" label="ID" width="55" align="center"></el-table-column>
      <el-table-column prop="carNumber" :min-width="100" label="车牌"></el-table-column>
      <el-table-column prop="brand" :min-width="120" align="center" label="品牌"></el-table-column>
      <el-table-column prop="model" :min-width="120" align="center" label="车型"></el-table-column>
      <el-table-column prop="colour" :min-width="120" align="center" label="车身颜色"></el-table-column>
      <el-table-column prop="price" :min-width="120" align="center" label="价格（元）"></el-table-column>
      <el-table-column prop="intro" :min-width="200" align="center" label="详情">
        <template v-slot="{row}">
          <el-tooltip :content="row.intro">
            <div class="intro-box">
              {{ row.intro }}
            </div>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column :min-width="220" align="center" label="展示图">
        <template v-slot="{row}">
          <div class="flex-row ">
            <el-image
                style="width: 50px; height: 50px"
                :src="item"
                class="bg-light-blue flex-shrink"
                v-for="(item,i) of row.images||[]"
                :preview-src-list="row.images||[]"
                :initial-index="i+1">
            </el-image>
          </div>
        </template>
      </el-table-column>


      <el-table-column label="操作" :width="120" align="center" fixed="right">
        <template #default="{row}">
          <el-button type="text" icon="el-icon-edit" @click="toggleEditorModal(true,row)" size="mini">编辑</el-button>
          <el-button type="text" icon="el-icon-delete" @click="onDestroy(row)" size="mini">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!--列表数据 end-->


    <!--分页组件 start-->
    <div class="pagination">
      <el-pagination
          background layout="total, prev, pager, next"
          :current-page="pageMeta.current_page"
          :page-size="pageMeta.limit" :total="pageMeta.total"
          @current-change="onPageChange"></el-pagination>
    </div>
    <!--分页组件 end-->
    <!--分类编辑、新增弹框 start-->
    <el-dialog
        v-model="formData.show"
        :title="formData.data.id>0?'编辑':'新增'"
        width="70%">
      <el-form
          ref="formRefName"
          :rules="rules"
          :model="formData.data"
          label-width="100px">
        <el-form-item label="服务包" prop="carNumber">
          <el-checkbox-group v-model="formData.serverIds">
            <el-checkbox v-for="(item,i) of services" :label="item.id" :key="i">{{ item.name }}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="车牌" prop="carNumber">
          <el-input v-model="formData.data.carNumber" placeholder="请填写车牌"></el-input>
        </el-form-item>
        <el-form-item label="品牌" prop="brand">
          <el-input v-model="formData.data.brand" placeholder="请填写品牌"></el-input>
        </el-form-item>
        <el-form-item label="车型" prop="model">
          <el-input v-model="formData.data.model" placeholder="请填写车型"></el-input>
        </el-form-item>
        <el-form-item label="车身颜色" prop="colour">
          <el-input v-model="formData.data.colour" placeholder="请填写车身颜色"></el-input>
        </el-form-item>
        <el-form-item label="描述/介绍" prop="intro">
          <el-input type="textarea" v-model="formData.data.intro" placeholder="请填写车辆描述/介绍"></el-input>
        </el-form-item>
        <el-form-item label="租价(元/日)" prop="price">
          <el-input-number v-model="formData.data.price" placeholder="单日租赁价格"></el-input-number>
        </el-form-item>
        <el-form-item label="图片展示">
          <el-upload
              v-if="formData.show"
              action="#"
              :on-remove="(_,files)=>formData.images = files"
              :file-list="formData.images"
              :on-preview="onImgPreview"
              :before-upload="onUpload"
              list-type="picture-card">
            <div style="height: 100%;" class="col-align-center">
              <Plus style="width: 40px;height: 40px"/>
            </div>
          </el-upload>
        </el-form-item>

      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button size="small" @click="toggleEditorModal(false)">取消</el-button>
          <el-button size="small" type="primary" @click="onSubmit()">提交保存</el-button>
        </div>
      </template>
    </el-dialog>
    <!--分类编辑、新增弹框 end-->

    <el-dialog v-model="formData.imgViewer">
      <el-image :key="formData.imgUrl" :src="formData.imgUrl"/>
    </el-dialog>
  </div>


</template>

<script>
import {defineComponent, reactive, ref, toRaw} from "vue"
import {usePageMeta} from "../../hooks/usePageTableData";
import {deepClone, isEmpty} from "../../utils/helpers";
import Toast from "../../utils/Toast";
import Goods from "../../api/modules/Goods";
import Service from "../../api/modules/Service";
import {Plus} from "@element-plus/icons-vue";
import Media from "../../api/modules/Media";

export default defineComponent({
  name: "Goods",
  components: {
    Plus
  },
  data() {
    return {
      rules: {
        carNumber: [
          {required: true, message: "请填写车牌"}
        ],
        brand: [
          {required: true, message: "请填写品牌"}
        ],
        model: [
          {required: true, message: "请填写车型"}
        ],
        colour: [
          {required: true, message: "请填写车身颜色"}
        ],
        intro: [
          {required: true, message: "请填写描述/介绍"}
        ],
        price: [
          {type: 'number', min: 0, max: 99999, transform: v => Number(v) || '', message: "价格范围在0~99999之间"},
        ]
      },
    }
  },
  setup() {
    const formRefName = ref(null);
    const pageHandle = usePageMeta();
    const params = reactive({
      filter: "",
    });
    const services = ref([]);
    const tableData = ref([]);


    getServices(); // 车辆服务包列表
    onPageChange(1); // 初始化时直接请求一次分类列表

    const formData = reactive({
      show: false,
      imgViewer: false,
      imgUrl: "",
      images: [], // 图片展示，多张
      serverIds: [], // 汽车服务包id，示例：id1,id2...
      data: {
        id: 0,
        serverIds: "",
        images: "",
        brand: '', // 品牌
        intro: '', // 描述/介绍
        model: '', // 型号
        price: '', // 单日租赁价格
        colour: '', // 车身颜色
        carNumber: '', // 车牌号码
      }
    });


    const _formData = deepClone(toRaw(formData));

    async function toggleEditorModal(show, row = {}) {
      if (row.id) { // 新增
        try {
          const {data} = await Goods.info(row.id)
          if (isEmpty(data)) {
            Toast.warning("查询汽车商品信息失败");
            return;
          }
          try {
            formData.images = (JSON.parse(data.images) || []).map(v => {
              return {
                name: v,
                url: v,
              }
            });
          } catch (e) {
            formData.images = [];
          }
          formData.serverIds = (data.carServerList || []).map(v => v.id);
          formData.data = Object.assign({}, _formData.data, row);
        } catch (e) {

        }
      } else if (show) { // 编辑
        formData.images = [];
        formData.serverIds = [];
        formData.data = Object.assign({}, _formData.data, row);
      }
      formData.show = show;
      if (formRefName.value) {
        formRefName.value.resetFields();
      }

    }

    function onSubmit() {
      if (!formRefName.value) {
        Toast.error('找不到表单')
        return;
      }
      formRefName.value.validate(async (valid) => {
        if (!valid) {
          return;
        }
        const _formData = deepClone(toRaw(formData)).data;
        try {
          let res = {}
          delete _formData.createTime;
          delete _formData.updateTime;
          _formData.images = JSON.stringify(formData.images.map(v => v.url))
          _formData.serverIds = JSON.stringify(formData.serverIds)
          if (_formData.id > 0) {
            res = await Goods.update(_formData)
            onPageChange()
          } else { // 新增操作
            delete _formData.id;
            res = await Goods.create(_formData);
            onPageChange(1)
          }
          Toast.success(res.message || '操作成功');
          toggleEditorModal(false)
        } catch (e) {
          Toast.error(e.message);
        }

      })
    }

    async function onDestroy(row) {
      const canDestroy = await Toast.confirm();
      if (!canDestroy) {
        return;
      }
      try {
        const res = await Goods.destroy(row.id);
        Toast.success(res.message || '删除成功');
        if (tableData.value.length === 1) {
          onPageChange(1);
        } else {
          onPageChange();

        }
      } catch (e) {
        console.log(e)
        Toast.error(e.message || '删除失败')
      }
    }

    // 车辆服务包
    async function getServices() {
      try {
        const {data} = await Service.lists({
          filter: "",
          index: 1,
          limit: 999999,
        });
        services.value = data.data || [];
        console.log(services)
      } catch (e) {
        console.log(e);
      }
    }

    async function onPageChange(page) {
      const pageMeta = deepClone(toRaw(pageHandle.pageMeta.value));
      if (page) {
        pageMeta.index = page;
      }
      try {
        const {data} = await Goods.lists({
          ...pageMeta,
          ...params,
        });
        tableData.value = (data.data || []).map(v => {
          try {
            v.images = JSON.parse(v.images)
          } catch (e) {
            v.images = [];
          }
          return v
        });
        pageHandle.updatePageMeta(pageMeta.index, data.count);

      } catch (e) {
        console.log(e);
      }
    }

    function onUpload(file) {
      Media.upload(file).then(({data}) => {
        if (data) {
          formData.images.push(data);
        }
      }).catch(console.log)
      return false
    }

    function onImgPreview(file) {
      console.log(file)
      formData.imgViewer = true;
      formData.imgUrl = file.url;
    }

    return {
      ...pageHandle,
      params,
      onImgPreview,
      onUpload,
      services,
      onSubmit,
      formData,
      formRefName,
      toggleEditorModal,
      onDestroy,
      tableData,
      onPageChange,
    }
  },
})
</script>

<style lang="scss" scoped>
.intro-box {
  max-height: 70px;
  overflow: hidden;
}
</style>
